<?php
//后根序遍历目录, 读取所有子目录和文件
//张志斌 954861399@qq.com
class Dir
{
	public $dir = '';
	public $fileList = array();

	public function __construct($dir)
	{
		$stack = array();
		$this->dir = $dir = realpath($dir);
		$currentDir = $dir.DIRECTORY_SEPARATOR;
		$current = array_slice(scandir($dir), 2); //去掉 . 和 ..

		if (!empty($current)) {
			do {
				$isOver = 1;
				foreach ($current as $k => $fileName) {
					if (substr($fileName, 0, 1) != '.') {
						$pathName = $currentDir.$fileName;
						if (is_file($pathName)) {
							$this->fileList[] = $pathName;
						} elseif (is_dir($pathName) && count(scandir($pathName)) > 2) {
							//当前是目录, 就把其以后的数据压栈
							$tmp = array_slice($current, $k+1);
							$tmp['currentDir'] = $currentDir;
							array_push($stack, $tmp);

							$current = array_slice(scandir($pathName), 2);
							$currentDir = $pathName.DIRECTORY_SEPARATOR;

							$isOver = 0;
							break;
						}
					}
				}
				if ($isOver) { //没有入栈, 说明当前目录里全是文件
					$current = array_pop($stack);
					$currentDir = $current['currentDir'];
					unset($current['currentDir']);
				}

			} while(!empty($stack) || count($current));
		}
	}

	//读取所有子目录和文件, $dir目录最后不要有'/'
	public static function ini($dir)
	{
		return new self($dir);
	}

	//替换路径里的字符串
	public function replace($target, $replace='')
	{
		foreach ($this->fileList as $k => $v) {
			$this->fileList[$k] = str_replace($target, $replace, $v);
		}
		return $this;
	}
    
    //替换路径里的字符串
    public function pregReplace($pattern, $replace='')
    {
        foreach ($this->fileList as $k => $v) {
            $this->fileList[$k] = preg_replace("#$pattern#i", $replace, $v);
        }
        return $this;
    }
	
	//筛选获取指定的后缀
	public function extension($ext)
	{
		foreach ($this->fileList as $k => $v) {
			$extension = pathinfo($v, PATHINFO_EXTENSION);
			if (strtolower($extension) != $ext) {
				unset($this->fileList[$k]);
			}
		}
		return $this;
	}
	
	public function sortFiles($isReverse = FALSE)
    {
        if ($isReverse) {
            rsort($this->fileList);
        } else {
            sort($this->fileList);
        }
        
        return $this;
    }

}